<template>
  <Dialog title="工序汇报" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <!-- 工序基本信息（只读显示） -->
      <el-row :gutter="20">
        <el-col :span="12">
          <div style="margin-bottom: 18px">
            <span style="color: #606266">工序名称：</span>
            <span>{{ processInfo.name }}</span>
          </div>
        </el-col>
        <el-col :span="12">
          <div style="margin-bottom: 18px">
            <span style="color: #606266">负责人员：</span>
            <span>{{ processInfo.userName }}</span>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <div style="margin-bottom: 18px">
            <span style="color: #606266">计费方式：</span>
            <span>{{ processInfo.type }}</span>
          </div>
        </el-col>
        <el-col :span="12">
          <div style="margin-bottom: 18px">
            <span style="color: #606266">加工单价：</span>
            <span>{{ processInfo.price }}</span>
          </div>
        </el-col>
      </el-row>

      <el-divider content-position="left">本次汇报信息</el-divider>

      <!-- 本次汇报信息 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="加工人员" prop="userId">
            <CascaderUser v-model="formData.userId" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合格数量" prop="passCount">
            <el-input-number
              v-model="formData.passCount"
              placeholder="请输入合格数量"
              style="width: 100%"
              :min="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报废数量" prop="scrapCount">
            <el-input-number
              v-model="formData.scrapCount"
              placeholder="请输入报废数量"
              style="width: 100%"
              :min="0"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="加工开始" prop="workBeginTime">
            <el-date-picker
              v-model="formData.workBeginTime"
              type="datetime"
              value-format="x"
              placeholder="请选择加工开始"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="加工结束" prop="workEndTime">
            <el-date-picker
              v-model="formData.workEndTime"
              type="datetime"
              value-format="x"
              placeholder="请选择加工结束"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="合计用时" prop="allTime">
        <el-input v-model="formData.allTime" placeholder="请输入合计用时">
          <template #append>小时</template>
        </el-input>
      </el-form-item>

      <el-form-item label="单据备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">关 闭</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ProduceProcessItemsApi, ProduceProcessItems } from '@/api/erp/produce/process/items'
import CascaderUser from '@/components/CascaderUser/CascaderUser.vue'

/** ERP 生产计划工序项 表单 */
defineOptions({ name: 'ProducePlanProcessItemsForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

// 工序基本信息（只读）
const processInfo = ref({
  name: '',
  userName: '',
  type: '',
  price: ''
})

const formData = ref({
  id: undefined,
  planNo: undefined,
  planId: undefined,
  userId: undefined,
  checkUserId: undefined,
  processId: undefined,
  workBeginTime: undefined,
  workEndTime: undefined,
  allTime: undefined,
  passCount: undefined,
  scrapCount: undefined,
  remark: undefined
})
const formRules = reactive({
  planId: [{ required: true, message: '生产计划单id不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '加工人员不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (processRow: any, type: string = 'create', id?: number) => {
  dialogVisible.value = true
  formType.value = type
  resetForm()

  // 设置工序基本信息
  if (processRow) {
    processInfo.value = {
      name: processRow.name || '',
      userName: processRow.userName || '',
      type: processRow.type || '',
      price: processRow.price || ''
    }
    formData.value.planId = processRow.planId
    formData.value.processId = processRow.id
  }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProduceProcessItemsApi.getProduceProcessItems(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProduceProcessItems
    if (formType.value === 'create') {
      await ProduceProcessItemsApi.createProduceProcessItems(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProduceProcessItemsApi.updateProduceProcessItems(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planNo: undefined,
    planId: undefined,
    userId: undefined,
    checkUserId: undefined,
    process: undefined,
    workBeginTime: undefined,
    workEndTime: undefined,
    allTime: undefined,
    passCount: undefined,
    scrapCount: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}
</script>
